/**
 * BaseController.java created by zhangzhidong 
 * at 下午6:24:52 2016年4月18日
 */
package controllers;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.edu.bjtu.labsys.constant.Constant;
import cn.edu.bjtu.labsys.settings.ApplicationConfiguration;
import pojo.ResCode;


/**
 * @author zhangzhidong
 *
 */
public abstract class BaseController implements ServletContextAware,ApplicationEventPublisherAware {
	protected Logger logger;
	private static ApplicationConfiguration appProperties = null;
	private static DiskFileItemFactory dfif = new DiskFileItemFactory();
	private static ServletFileUpload sfu = new ServletFileUpload(dfif);
	protected static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	protected static ObjectMapper mapper  = new ObjectMapper();
	protected ApplicationEventPublisher applicationEventPublisher;
	static{
		mapper.setDateFormat(sdf);
	}
	public static final ResCode SUCCESS = new ResCode(0,"success");
	public static final ResCode ERROR = new ResCode(400,"error");
	public static final ResCode ParamsError = new ResCode(400,"params error");

	protected void logInfo(Object message) {
		this.logger = Logger.getLogger(this.getClass());
		logger.info(message);
	}
	protected ModelAndView renderView(String viewName,Map<String,?> model) {
		return new ModelAndView(viewName, model);
	}
	protected ModelAndView renderView(String viewName,String name,Object obj) {
		return new ModelAndView(viewName, name, obj);
	}
	
	protected String getAppProperties(String forKey) {
		return appProperties.getProperty(forKey);
	}
	protected Properties getApplicationPropertis(){
		return appProperties;
	}
	protected void downloadFile(HttpServletRequest req,HttpServletResponse res) {
		
	}
	protected String jsonDump(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return jsonDump(ERROR);
		}
	}
	protected <T> T fromJson(String content,Class<T> clz){
		try {
			return mapper.readValue(content, clz);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	protected static WebApplicationContext wac = null;
	public void setServletContext(ServletContext servletContext) {
		appProperties = (ApplicationConfiguration)servletContext.getAttribute(Constant.APPLICATION_CONFIGURATION_KEY);
		wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
	}
	protected String webAppPath(){
		return wac.getServletContext().getRealPath("/");
	}
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher){
		this.applicationEventPublisher = applicationEventPublisher;
	}
	
	
	/**
	 * 处理post过来的包括文件的http请求
	 * 下午8:49:14 2015年9月21日
	 * @param req
	 * @param pathToSave 保存文件的路径,应该以/结尾
	 * @return
	 */
//	final protected int saveFileFromRequestToPath(HttpServletRequest req,File pathToSave){
// 
//        List<FileItem> fileItems = null;;
//		try {
//			fileItems = sfu.parseRequest(req);
//		} catch (FileUploadException e) {
//			// TODO Auto-generated catch block
//			return 0;
//		}  
//		int fileCount = 0;
//         Iterator<FileItem> iter = fileItems.iterator();  
////         List<String> fileNames = new ArrayList<String>();  
//         while (iter.hasNext()) {  
//             FileItem item = (FileItem) iter.next();
//             fileCount ++;
//             if (!item.isFormField()) {
//            	 // 文件  
//                 String oldFileName = item.getName();
//                 //暂时不重新命名
////                 String newFileName = null;  
////                 int delimiter = oldFileName.lastIndexOf("/");  
////                 if (delimiter == -1)  
////                     newFileName = oldFileName.substring(delimiter + 1);  
////                 else  
////                     newFileName = oldFileName;  
////                 fileNames.add(newFileName);  
//                 try {
//					item.write(new File(pathToSave,oldFileName));
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//					continue;
//				}  
//             } else { // 表单  
//            	 //ignore
//                 /*String fieldName = item.getFieldName();  
//                 if ("uploader".equals(fieldName)) {  
//                     uploader = item.getString();  
//                 } else if ("date".equals(fieldName)) {  
//                     date = item.getString();  
//                 }  */
//             }  
//         }  
//		
//		return fileCount;
//	}

	
	
	
}
